﻿using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Peninsula.Web.Areas.Backstage.Models.Account;
using System.Reflection;
using System;
using Peninsula.Web.Infrastructure;
using Peninsula.Utility.Extensions;
using Peninsula.Web.Models.Sessions;
using Peninsula.DataAccess.POCO;
using Peninsula.Site.Data.Result;
using Peninsula.Site.Data;
using MvcPaging;
using Peninsula.Site.Data.Constant;
using Peninsula.Utility.Helper;
using Peninsula.Site.Data.Models;
using Peninsula.Account.common;
using Ninject;

namespace Peninsula.Web.Areas.Backstage.Controllers
{
    public class AccountController : AdminBaseController
    {
        public Dictionary<string, string> GroupIcons = new Dictionary<string, string>
        {
            { "用户管理", "fa-user"},
            { "系统功能", "fa-cogs"},
            { "账户管理", "fa-users"},
            { "开发者功能（慎点）", "fa-legal"},
            { "基础设定", "fa-user-md"},
            { "求助管理", "fa-bullhorn" },
            { "通知管理", "fa-volume-up" },
            { "订单管理", "fa-money" },
            { "基本管理", "fa-user-md"}

        };

        TotalList list = new TotalList();


        string[] CateporyMonth = new string[] { "1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月" };

        [Inject]

        public  IServices.IStoreService StoreService { get; set; }
        [Inject]
        public IServices.IStoreRestatisticsService StoreRestatisticsService { get; set; }

        #region 登录登出相关

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="returnUrl"></param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public ActionResult Login(string returnUrl)
        {
            if(AdminManager.All().Count() == 0)
            {
                IniteData();
            }
            SetPageTitle("后台登陆");
            return View(new LoginViewModel() { ReturnUrl = returnUrl });
        }
        
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public ActionResult Login(LoginViewModel model)
        {
            bool isLockout = false;
            if (ModelState.IsValid && AdminManager.ValidateAdmin(model.AdminName, model.Password, out isLockout))
            {
                var admin = AdminManager.Get(model.AdminName);

                IEnumerable<Permission> allPermission = null;
                if (admin.IsSuperAdmin)
                {
                    allPermission = PermissionManager.All();
                }
                else
                {
                    allPermission = admin.Roles.SelectMany(r => r.Permissions);
                }

                AdminSignIn(new AdminSession(admin, allPermission), model.RememberMe);

                if (model.ReturnUrl.IsNullOrWhiteSpace() || model.ReturnUrl.Equals("/"))
                {
                   // return Redirect("/Admin/FishcooV2/User");
                    return RedirectToRoute(RouteConfig.AdminDefault, new { controller = "Home", action = "Index"});
                }
                else
                {
                    return Redirect(model.ReturnUrl);
                }
            }

            if (isLockout)
            {
                ModelState.AddModelError("", "尝试错误过多，账户被锁定！");
            }
            else
            {
                ModelState.AddModelError("", "账户密码错误！");
            }
            return View(model);
        }

        
        /// <summary>
        /// 登出
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        public ActionResult Logout()
        {
            base.HouseholdsSignOut();
            return RedirectToAction("Login");
        }

        #endregion 登录登出相关

        #region 管理员管理
        
        /// <summary>
        ///  获取所有管理员
        /// </summary>
        /// <param name="viewModel"></param>
        /// <returns></returns>
        [PermissionInfo("管理员管理", "账户管理")]
        public ActionResult AdminList(AdminPagedListModel viewModel)
        {
            viewModel.PagedList = AdminManager.All()
                .Where(a => a.UserName.ContainsNoCase(viewModel.Keyword)
                 && (!viewModel.IsSuperAdmin.HasValue || a.IsSuperAdmin == viewModel.IsSuperAdmin))
                .OrderBy(a => a.UserName)
                .ToPagedList(viewModel.PageIndex, viewModel.Size);

            viewModel.QueryParameter = GetParameterFromQueryString();

            SetPageTitle("管理员管理");
            SetBreadcrumb(parentName: "账户管理");
            return View(viewModel);
        }

        /// <summary>
        /// 删除管理员
        /// </summary>
        public ActionResult DeleteAdmin(string id)
        {
            var result = new JsonResultData();
            result.RunWithTry(data =>
            {
                AdminManager.Delete(a => a.Id == id);
                data.Success = true;
                data.ReloadPage = true;
                data.AddMessage("删除成功！");
            });
            return JsonAllowGet(result);
        }

        /// <summary>
        /// 创建管理员
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult CreateOrEditAdmin(string id)
        {
            Peninsula.DataAccess.POCO.Admin admin = null;

            if (id.IsNotNullAndNotWhiteSpace())
            {
                admin = AdminManager.Get(a => a.Id == id);
                if (admin.IsNull())
                {
                    return RedirectToError("没有找到对应的管理员", code: 404);
                }
                ViewBag.IsEdit = true;
            }
            else
            {
                admin = new Peninsula.DataAccess.POCO.Admin();
                ViewBag.IsEdit = false;
            }

            ViewBag.AllRoles = RoleManager.All();
            SetPageTitle(ViewBag.IsEdit ? "编辑管理员" : "创建管理员");
            SetBreadcrumb(parentName: "账户管理");
            return View(admin);
        }

        /// <summary>
        /// 创建管理员
        /// </summary>
        /// <param name="isEdit"></param>
        /// <param name="postAdmin"></param>
        /// <param name="role"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult CreateOrEditAdmin(bool isEdit, Peninsula.DataAccess.POCO.Admin postAdmin, string[] role)
        {
            var result = new JsonResultData();

            result.RunWithTry(item =>
            {
                if (isEdit)
                {
                    ModelState.Remove("Password");
                }
                if (ModelState.IsValid)
                {
                    role = role ?? new string[0];
                    var face = SaveFile("FaceImg", FileSaveRule.AdminFaceSavePath);
                    if (isEdit)
                    {
                        var adminEntity = AdminManager.Get(a => a.Id == postAdmin.Id);
                        adminEntity.FaceImgPath = face ?? adminEntity.FaceImgPath;

                        ValueCopyHelper.CopyProperty(adminEntity, postAdmin, false,
                            nameof(postAdmin.TrueName),
                           // nameof(postAdmin.Dept),
                           // nameof(postAdmin.Postion),
                            nameof(postAdmin.Email),
                            nameof(postAdmin.Phone),
                            //nameof(postAdmin.Phone2),
                            nameof(postAdmin.IsSuperAdmin),
                            nameof(postAdmin.IsLockedOut));
                        

                        adminEntity.SetUpdateInfo(AdminSession.AdminEntity.UserName);

                        //删除旧的角色
                        adminEntity.Roles.Where(r => !role.Contains(r.Id)).ToList().ForEach(r => adminEntity.Roles.Remove(r));
                        //添加新角色
                        RoleManager.All().Where(r => role.Contains(r.Id))
                            .ForEach(r => adminEntity.Roles.Add(r));

                        AdminManager.Update(adminEntity);
                    }
                    else
                    {
                        postAdmin.FaceImgPath = face;
                        RoleManager.All().Where(r => role.Contains(r.Id))
                            .ForEach(r => postAdmin.Roles.Add(r));

                        postAdmin.SetCreateAndUpdateInfo(AdminSession.AdminEntity.UserName);

                        AdminManager.Add(postAdmin);
                    }

                    result.Success = true;
                    result.RedirectUrl = Url.Action("AdminList");
                    result.AddMessage("保存成功！");
                }
                else
                {
                    result.AddModelValidErrorMessage(ModelState);
                }
            });

            return Json(result);
        }



        #endregion 管理员管理

        #region 角色管理

        /// <summary>
        /// 获取角色列表
        /// </summary>
        /// <param name="viewModel"></param>
        /// <returns></returns>
        [PermissionInfo("角色管理", "账户管理")]
        public ActionResult RoleList(PagedListModel<Role> viewModel)
        {
            SetPageTitle("角色管理");
            SetBreadcrumb(parentName: "账户管理");

            viewModel.PagedList = RoleManager.All()
                .Where(r => r.RoleName.ContainsNoCase(viewModel.Keyword))
                .OrderBy(r => r.RoleName)
                .ToPagedList(viewModel.PageIndex, viewModel.Size);

            viewModel.QueryParameter = GetParameterFromQueryString();

            return View(viewModel);
        }

        /// <summary>
        /// 创建角色
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult CreateOrEditRole(string id)
        {
            Role role = null;

            if (id.IsNotNullAndNotWhiteSpace())
            {
                role = RoleManager.Get(r => r.Id == id);
                if (role.IsNull())
                {
                    return RedirectToError("没有找到对应的角色", code: 404);
                }
                ViewBag.IsEdit = true;
            }
            else
            {
                role = new Role();
                ViewBag.IsEdit = false;
            };

            ViewBag.PermissionJsonTree = BuildPermissionTreeViewModel(PermissionManager.All().Where(p => p.Parent_Id == null || p.Parent_Id == ""), role.Permissions.Select(p => p.Id).ToArray())
                                .ToJson(JsonExtensions.PropertyNaming.CamelCase);

            SetPageTitle(ViewBag.IsEdit ? "编辑角色" : "创建角色");
            SetBreadcrumb(parentName: "账户管理");
            return View(role);
        }

        /// <summary>
        /// 创建角色
        /// </summary>
        /// <param name="isEdit"></param>
        /// <param name="postRole"></param>
        /// <param name="PermissionId"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult CreateOrEditRole(bool isEdit, Role postRole, string PermissionId)
        {
            var result = new JsonResultData();

            result.RunWithTry(item =>
            {
                if (ModelState.IsValid)
                {
                    string[] permissionIdArr = PermissionId.IsNullOrWhiteSpace()
                                            ? new string[0]
                                            : PermissionId.Split(',');

                    if (isEdit)
                    {
                        var roleEntity = RoleManager.Get(r => r.Id == postRole.Id);

                        ValueCopyHelper.CopyProperty(roleEntity, postRole, false, 
                            nameof(postRole.RoleName),
                            nameof(postRole.Description));

                        roleEntity.SetUpdateInfo(AdminSession.AdminEntity.UserName);

                        //删除旧的权限
                        roleEntity.Permissions.Where(p => !permissionIdArr.Contains(p.Id)).ToList().ForEach(p => roleEntity.Permissions.Remove(p));
                        //添加新权限
                        PermissionManager.All().Where(p => permissionIdArr.Contains(p.Id))
                        .ForEach(p => roleEntity.Permissions.Add(p));

                        RoleManager.Update(roleEntity);
                    }
                    else
                    {
                        PermissionManager.All().Where(p => permissionIdArr.Contains(p.Id)).ToList()
                            .ForEach(p => postRole.Permissions.Add(p));

                        postRole.SetCreateAndUpdateInfo(AdminSession.AdminEntity.UserName);

                        RoleManager.Add(postRole);
                    }

                    result.Success = true;
                    result.RedirectUrl = Url.Action("RoleList");
                    result.AddMessage("保存成功！");
                }
                else
                {
                    result.AddModelValidErrorMessage(ModelState);
                }
            });

            return Json(result);
        }

        /// <summary>
        /// 删除角色
        /// </summary>
        public ActionResult DeleteRole(string id)
        {
            var result = new JsonResultData();
            result.RunWithTry(data =>
            {
                RoleManager.Delete(r => r.Id == id);
                data.Success = true;
                data.ReloadPage = true;
                data.AddMessage("删除成功！");
            });
            return JsonAllowGet(result);
        }

        /// <summary>
        /// 移除管理员的某个角色
        /// </summary>
        public ActionResult DeleteAdminRole(string adminId, string roleId)
        {
            var result = new JsonResultData();
            result.RunWithTry(data =>
            {
                var admin = AdminManager.Get(a => a.Id == adminId);
                var role = RoleManager.Get(r => r.Id == roleId);

                admin.Roles.Remove(role);

                AdminManager.Update(admin);

                data.AddMessage("移除角色成功！");
                data.Success = true;
                data.ReloadPage = true;
            });
            return JsonAllowGet(result);
        }

        #endregion 角色管理

        #region 权限/菜单管理

        /// <summary>
        /// 获取菜单/权限
        /// </summary>
        /// <returns></returns>
        [PermissionInfo("权限/菜单列表", "账户管理")]
        public ActionResult PermissionList()
        {
            SetPageTitle("权限列表");
            SetBreadcrumb(parentName: "账户管理");

            return View(PermissionManager.All().Where(p => p.Parent_Id == null).OrderBy(p => p.Order).ToList());
        }

        /// <summary>
        /// 保存权限
        /// </summary>
        /// <param name="orderInfo"></param>
        /// <returns></returns>
        public ActionResult SavePermissionOrder(string orderInfo)
        {
            var result = new JsonResultData();
            result.RunWithTry(data =>
            {
                var nestableOrderInfo =
                     orderInfo.ToObject<List<NestableNote>>(JsonExtensions.PropertyNaming.CamelCase);

                var newPermissions = SetPermissionRelation(nestableOrderInfo, PermissionManager.All().ToList());
                newPermissions.ForEach(p => PermissionManager.Update(p));
                //刷新权限缓存
                var allPermissions = PermissionManager.GetAllPermissionCache(true);

                data.Success = true;
                data.ReloadPage = true;
                data.AddMessage("保存成功！");
            });
            return JsonAllowGet(result);
        }

        /// <summary>
        /// 创建权限
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult CreateOrEditPermission(string id)
        {
            Permission permission = null;

            if (id.IsNotNullAndNotWhiteSpace())
            {
                permission = PermissionManager.Get(p => p.Id == id);
                if (permission.IsNull())
                {
                    return RedirectToError("没有找到对应的角色", code: 404);
                }
                ViewBag.IsEdit = true;
            }
            else
            {
                permission = new Permission();
                ViewBag.IsEdit = false;
            };
            var permissionDropdownLostItems = GetPermissionDropdownListItems(PermissionManager.All().Where(p => p.Parent_Id == null && p.Id != id).ToList(), "", id);
            permissionDropdownLostItems.Insert(0, new SelectListItem { Text = "无", Value = "" });
            ViewBag.PermissionSelectItems = permissionDropdownLostItems;

            SetPageTitle(ViewBag.IsEdit ? "编辑权限" : "创建权限");
            SetBreadcrumb(parentName: "账户管理");
            return View(permission);
        }

        /// <summary>
        ///  创建权限
        /// </summary>
        /// <param name="isEdit"></param>
        /// <param name="postPermission"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult CreateOrEditPermission(bool isEdit, Permission postPermission)
        {
            var result = new JsonResultData();

            result.RunWithTry(item =>
            {
                if (ModelState.IsValid)
                {
                    if (isEdit)
                    {
                        var permissionEntity = PermissionManager.Get(r => r.Id == postPermission.Id);

                        ValueCopyHelper.CopyProperty(permissionEntity, postPermission, false,
                            nameof(postPermission.PermissionName),
                            nameof(postPermission.Description),
                            nameof(postPermission.IsMenu),
                            nameof(postPermission.Action),
                            nameof(postPermission.Controller),
                            nameof(postPermission.Url),
                            nameof(postPermission.CssClass),
                            nameof(postPermission.Parent_Id),
                            nameof(postPermission.Order));

                        permissionEntity.SetUpdateInfo(AdminSession.AdminEntity.UserName);

                        PermissionManager.Update(permissionEntity);
                    }
                    else
                    {
                        postPermission.SetCreateAndUpdateInfo(AdminSession.AdminEntity.UserName);

                        PermissionManager.Add(postPermission);
                    }

                    result.Success = true;
                    result.RedirectUrl = Url.Action("PermissionList");
                    result.AddMessage("保存成功！");

                    //刷新权限缓存
                    var allPermissions = PermissionManager.GetAllPermissionCache(true);
                }
                else
                {
                    result.AddModelValidErrorMessage(ModelState);
                }
            });

            return Json(result);
        }

        /// <summary>
        /// 删除权限
        /// </summary>
        public ActionResult DeletePermission(string id)
        {
            var result = new JsonResultData();
            result.RunWithTry(data =>
            {
                var permission = PermissionManager.Get(a => a.Id == id);
                var childIds = permission.Chindren?.Select(p => p.Id)?.ToList() ?? new List<string>();
                childIds.Add(id);
                PermissionManager.Delete(a => childIds.Contains(a.Id));
                data.Success = true;
                data.ReloadPage = true;
                data.AddMessage("删除成功！");
            });
            return JsonAllowGet(result);
        }

        #endregion 权限/菜单管理


        #region 账户修改

        /// <summary>
        /// 个人中心
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult MyProfile()
        {
            Peninsula.DataAccess.POCO.Admin admin = null;
            admin = AdminSession.AdminEntity;

            ViewBag.AllRoles = RoleManager.All();
            SetPageTitle("账户设置");
            return View(admin);
        }

        /// <summary>
        /// 修改资料
        /// </summary>
        /// <param name="postAdmin"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult MyProfile(ProfileModel postAdmin)
        {
            var result = new JsonResultData();

            result.RunWithTry(item =>
            {
                if (postAdmin.NewPassword.IsNullOrWhiteSpace())
                {
                    ModelState.Remove("Password");
                }
                if (ModelState.IsValid)
                {
                    var adminEntity = AdminSession.AdminEntity;
                    
                    var faceImg = SaveFile("FaceImg", FileSaveRule.AdminFaceSavePath);
                    if (faceImg.IsNotNull())
                    {
                        adminEntity.FaceImgPath = faceImg;
                    }

                    ValueCopyHelper.CopyProperty(adminEntity, postAdmin, false,
                        nameof(postAdmin.TrueName),
                        // nameof(postAdmin.Dept),
                        // nameof(postAdmin.Postion),
                        nameof(postAdmin.Email),
                        nameof(postAdmin.Phone));
                        //nameof(postAdmin.Phone2));
                    
                    // 修改新密码
                    if (!AdminManager.SetIfChangePassword(adminEntity, postAdmin.Password, postAdmin.NewPassword))
                    {
                        result.Success = false;
                        result.AddMessage("密码错误！");
                    }
                    else
                    {
                        adminEntity.SetUpdateInfo(AdminSession.AdminEntity.UserName);
                        AdminManager.Update(adminEntity);

                        result.Success = true;
                        result.RedirectUrl = Url.Action("MyProfile");
                        result.AddMessage("保存成功！");
                    }
                }
                else
                {
                    result.AddModelValidErrorMessage(ModelState);
                }
            });

            return Json(result);
        }

        #endregion 账户修改

        #region private method

        /// <summary>
        /// 根据页面返回的树形结构，重新设置权限树
        /// </summary>
        private List<Permission> SetPermissionRelation(List<NestableNote> nestableNodes, List<Permission> allPermissions)
        {
            List<Permission> result = new List<Permission>();

            if (nestableNodes.IsNotEmpty())
            {
                int order = 1;
                foreach (var nNode in nestableNodes)
                {
                    var tmpPermission = allPermissions.FirstOrDefault(p => p.Id == nNode.id);
                    if (tmpPermission.IsNotNull())
                    {
                        tmpPermission.Order = order++;
                        tmpPermission.Parent_Id = null;
                        tmpPermission.Parent = null;
                        tmpPermission.Chindren.Clear();
                        foreach (var childPermission in SetPermissionRelation(nNode.children, allPermissions))
                        {
                            tmpPermission.Chindren.Add(childPermission);
                        }
                    }
                    PermissionManager.Update(tmpPermission);
                    result.Add(tmpPermission);
                }
            }

            return result;
        }

        /// <summary>
        /// 构建权限树
        /// </summary>
        private List<TreeViewNote> BuildPermissionTreeViewModel(IEnumerable<Permission> permissions, string[] hasPermissionIds = null)
        {
            if (permissions == null || permissions.Count() == 0)
            {
                return null;
            }

            List<TreeViewNote> result = new List<TreeViewNote>();
            foreach (var permission in permissions.ToList())
            {
                var note = new TreeViewNote()
                {
                    Text = permission.PermissionName,
                    Nodes = BuildPermissionTreeViewModel(permission.Chindren, hasPermissionIds),
                    ServerId = permission.Id,
                    State = new TreeViewNoteStatus() { Checked = hasPermissionIds.Contains(permission.Id) }
                };
                result.Add(note);
            }
            return result;
        }

        private List<SelectListItem> GetPermissionDropdownListItems(IEnumerable<Permission> permissions, string strOccupy = "", string currentPermissionId = "")
        {
            var result = new List<SelectListItem>();
            if (permissions.IsNotEmpty())
            {
                permissions.ForEach(p =>
                {
                    if (p.Id != currentPermissionId)
                    {
                        result.Add(new SelectListItem { Text = strOccupy + p.PermissionName, Value = p.Id });
                        result.AddRange(GetPermissionDropdownListItems(p.Chindren.ToList(), strOccupy + "------", currentPermissionId));
                    }
                });
            }
            return result;
        }

        #endregion private method


        #region init data

        //private ActionResult InitMenuData()
        //{
        //    #region 删除现有数据

        //    //PermissionManager.Delete(t => t.Parent_Id != null);
        //    //PermissionManager.Delete(t => t.Parent_Id == null);
        //    PermissionManager.All().Where(p => p.IsMenu).ToList()
        //       .ForEach(p => PermissionManager.Delete(p.PermissionName));//删除所有原本的菜单

        //    #endregion

        //    List<Type> controllers = Assembly.GetExecutingAssembly().GetTypes()
        //        .Where(t =>
        //        t.BaseType != null
        //        && t.BaseType.Name == "AdminBaseController"
        //        && t.Name != null
        //        && t.Name.EndsWith("Controller")
        //        && t.Namespace != null
        //        && t.Namespace.StartsWith("Test.Web.Areas.Bancktage.Controllers")).ToList();

        //    var properties = new List<PropertyInfo>();

        //    List<Permission> allNewPermissions = new List<Permission>();
        //    foreach (var controller in controllers)
        //    {
        //        string controllerName = controller.Name.Substring(0, controller.Name.Length - 10);
        //        var allMethods = controller.GetMethods().ToList();
        //        foreach (var method in allMethods)
        //        {
        //            var permissionAttr = method.GetCustomAttribute<PermissionInfoAttribute>();
        //            if (permissionAttr.IsNotNull() &&
        //                allNewPermissions.Count(p => p.PermissionName == permissionAttr.Name
        //                        && p.Controller == controllerName
        //                        && p.Action == method.Name) == 0)
        //            {
        //                var groupMenu = allNewPermissions.FirstOrDefault(p => p.PermissionName == permissionAttr.GroupName && p.Action == null);

        //                if (groupMenu.IsNull())
        //                {
        //                    groupMenu = new Permission()
        //                    {
        //                        PermissionName = permissionAttr.GroupName,
        //                        IsMenu = permissionAttr.IsMenu,
        //                        Action = null,
        //                        Controller = null,
        //                        //Area = "Admin",
        //                        CssClass = GroupIcons[permissionAttr.GroupName],
        //                        Order = permissionAttr.Order
        //                    };
        //                    allNewPermissions.Add(groupMenu);
        //                }
        //                groupMenu.Chindren.Add(new Permission()
        //                {
        //                    PermissionName = permissionAttr.Name,
        //                    IsMenu = permissionAttr.IsMenu,
        //                    Action = method.Name,
        //                    Controller = controllerName,
        //                    //Area = "Admin",
        //                    CssClass = permissionAttr.CssClass,
        //                    Order = permissionAttr.Order
        //                });
        //            }
        //        }
        //    }

        //    allNewPermissions = allNewPermissions.Distinct().ToList();//所有新增的菜单

        //    foreach (var newPermission in allNewPermissions)
        //    {
        //        PermissionManager.Add(newPermission);
        //    }
        //}

        /// <summary>
        /// 初始化菜单
        /// </summary>
        /// <returns></returns>
        public ActionResult InitMenuData()
        {
            #region 删除现有数据

            PermissionManager.All().Where(p => p.IsMenu).ToList()
                .ForEach(p => PermissionManager.Delete(p.PermissionName));//删除所有原本的菜单

            #endregion

            List<Type> controllers = Assembly.GetExecutingAssembly().GetTypes()
                .Where(t =>
                t.BaseType != null
                && t.BaseType.Name == "AdminBaseController"
                && t.Name != null
                && t.Name.EndsWith("Controller")
                && t.Namespace != null
                && t.Namespace.StartsWith("Peninsula.Web.Areas.Backstage.Controllers")).ToList();

            var properties = new List<PropertyInfo>();

            List<Permission> allNewPermissions = new List<Permission>();
            foreach (var controller in controllers)
            {
                string controllerName = controller.Name.Substring(0, controller.Name.Length - 10);
                var allMethods = controller.GetMethods().ToList();
                foreach (var method in allMethods)
                {
                    //获取每个方法的特性
                    var permissionAttr = method.GetCustomAttribute<PermissionInfoAttribute>();
                    if (permissionAttr.IsNotNull() &&
                        allNewPermissions.Count(p => p.PermissionName == permissionAttr.Name
                                && p.Controller == controllerName
                                && p.Action == method.Name) == 0)
                    {
                        var groupMenu = allNewPermissions.FirstOrDefault(p => p.PermissionName == permissionAttr.GroupName && p.Action == null);

                        if (groupMenu.IsNull())
                        {
                            groupMenu = new Permission()
                            {
                                PermissionName = permissionAttr.GroupName,
                                IsMenu = permissionAttr.IsMenu,
                                Action = null,
                                Controller = null,

                                CssClass = GroupIcons[permissionAttr.GroupName],
                                Order = permissionAttr.Order
                            };
                            allNewPermissions.Add(groupMenu);
                        }
                        groupMenu.Chindren.Add(new Permission()
                        {
                            PermissionName = permissionAttr.Name,
                            IsMenu = permissionAttr.IsMenu,
                            Action = method.Name,
                            Controller = controllerName,
                            CssClass = permissionAttr.CssClass,
                            Order = permissionAttr.Order
                        });
                    }
                }
            }

            allNewPermissions = allNewPermissions.Distinct().ToList();//所有新增的菜单
            PermissionManager.All().Where(p => p.IsMenu).ToList().ForEach(p => PermissionManager.Delete(p.PermissionName));//删除所有原本的菜单

            foreach (var newPermission in allNewPermissions)
            {
                PermissionManager.Add(newPermission);
            }
            return Content("ok");

        }
        /// <summary>
        /// 初始话数据
        /// </summary>
        private void IniteData()
        {

            #region 删除现有数据
            RoleManager.Delete(r => true);
            AdminManager.Delete(r => true);
            #endregion

            //初始化菜单
            InitMenuData();
            #region 初始化管理员数据



            Role role = new Role
            {
                RoleName = "超级管理员",
                Description = "啥权限都有"
            };

            Peninsula.DataAccess.POCO.Admin admin = new Peninsula.DataAccess.POCO.Admin
            {
                UserName = "admin",
                TrueName = "HANS",
                Email = "592576605@qq.com",
                IsSuperAdmin = true,
                IsLockedOut = false,
                Phone = "15659144619",
                Sex = Sex.Male,
                Password = PasswordProvider.EncryptPassword("123456")
            };

            // 权限设置

            RoleManager.Add(role);
            role.Permissions.ToList();
            PermissionManager.All().Where(t => true).ForEach(p => role.Permissions.Add(p));
            role.Admins.Add(admin);

            RoleManager.Update(role);

            #endregion

        }
        #endregion

        /// <summary>
        /// 平台管理员统计
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult AcctountTotal() {
            SetBreadcrumb(currentName: "订单统计");
            SetPageTitle("订单统计");
            TotalYearModel model = new TotalYearModel();
            model.DateKeyWord = null;
             model.Stores = StoreService.Entities.Select(
                 m => new SelectListItem()
                 {
                     Value = m.Id,
                     Text = m.Name
                 }).ToList();
            return View(model);

        }

        /// <summary>
        /// 平台管理员统计
        /// </summary>
        /// <param name="post"></param>
        /// <returns></returns>
       public JsonResult AcctountTotal( TotalYearModel post)
        {
            JsonResultData data = new JsonResultData();
            var year = HttpContext.Request.Form["dateKeyWord"];
            var storeId = HttpContext.Request.Form["storeId"];
            if (year == ""||storeId=="")
            {
                data.Success = false;
                data.AddMessage("统计年份不能为空！");
                return Json(data);
            }
            DateTime StartTotalTime = new DateTime(int.Parse(year), 1, 1);


            //添加横坐标
            foreach (var item in CateporyMonth)
            {
                list.listCatepory.Add(item);
            }

            Series number = new Series()
            {
                id = 0,
                name = "订单数量",
                type = "bar",
                data = new List<double>(),
                itemStyle = new itemStyle { normal = new normal { color = "#2EC7C9" } },
                markPoint = new markPoint { data = new List<data>() { new data { type = "max", name = "最大值" }, new data { type = "min", name = "最小值" } } },
                markLine = new markLine { data = new List<data>() { new data { type = "average", name = "平均值" } } }

            };

            Series money = new Series()
            {
                id = 1,
                name = "订单钱款",
                type = "bar",
                data = new List<double>(),
                itemStyle = new itemStyle { normal = new normal { color = "#FFBB73" } },
                markPoint = new markPoint { data = new List<data>() { new data { type = "max", name = "最大值" }, new data { type = "min", name = "最小值" } } },
                markLine = new markLine { data = new List<data>() { new data { type = "average", name = "平均值" } } }

            };


           

            if (StartTotalTime.Year == DateTime.Now.Year)//今年
            {
                IQueryable<StoreRestatistics> query = StoreRestatisticsService.Entities;
                for (DateTime dt = StartTotalTime; dt < DateTime.Now; dt = dt.AddMonths(1))
                {

                    query = query.Where(q => q.TotalDateTime.Value.Year == dt.Year && q.TotalDateTime.Value.Month == dt.Month && q.StoreId == storeId);
                    var storeRestatistics = query.SingleOrDefault();
                    if (query.Count() == 0)
                    {
                        number.data.Add(0);
                        money.data.Add(0);
                    }
                    else
                    {
                        number.data.Add(storeRestatistics.Number);
                        money.data.Add(storeRestatistics.TotalPrice.AsDouble());
                    }
                }


            }
            else if (StartTotalTime.Year < DateTime.Now.Year) //过去
            {
                DateTime FinishDateTime = StartTotalTime.AddYears(1);
                IQueryable<StoreRestatistics> query = StoreRestatisticsService.Entities;
                for (DateTime dt = StartTotalTime; dt < FinishDateTime; dt = dt.AddMonths(1))
                {
                    query = query.Where(q => q.TotalDateTime.Value.Year == dt.Year && q.TotalDateTime.Value.Month == dt.Month && q.StoreId == storeId);
                    var storeRestatistics = query.SingleOrDefault();
                    if (query.Count() == 0)
                    {
                        number.data.Add(0);
                        money.data.Add(0);
                    }
                    else
                    {
                        number.data.Add(storeRestatistics.Number);
                        money.data.Add(storeRestatistics.TotalPrice.AsDouble());
                    }

                }

            }
            else if (StartTotalTime.Year > DateTime.Now.Year)//将来
            {

            }
            else
            {

            }
            list.listLegend.Add(number.name);
            list.listLegend.Add(money.name);
            list.listSeries.Add(number);
            list.listSeries.Add(money);
            return Json(list);
        }

    }

 }
